﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Data;
using System.Collections;

namespace Web
{
    public class Utils
    {

        public static string GetFormString(string strName)
        {
            if (HttpContext.Current.Request.Form[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.Form[strName];
        }

        public static string GetIP()
        {
            string str2;
            string userHostAddress = string.Empty;
            userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (((str2 = userHostAddress) == null) || (str2 == ""))
            {
                userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if ((userHostAddress == null) || (userHostAddress == string.Empty))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }
            if ((userHostAddress != null) && !(userHostAddress == string.Empty))
            {
                return userHostAddress;
            }
            return "0.0.0.0";
        }

        public static string GetPageName()
        {
            string[] strArray = HttpContext.Current.Request.Url.AbsolutePath.Split(new char[] { '/' });
            return strArray[strArray.Length - 1].ToLower();
        }



        public static string GetQueryString(string strName)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.QueryString[strName].ToString().Trim();
        }

        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }

        public static string GetServerString(string strName)
        {
            if (HttpContext.Current.Request.ServerVariables[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.ServerVariables[strName].ToString();
        }

        public static string GetString(string strName)
        {
            if ("".Equals(GetQueryString(strName)))
            {
                return GetFormString(strName);
            }
            return GetQueryString(strName);
        }

        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }

        public static string GetUrlReferrer()
        {
            if (HttpContext.Current.Request.UrlReferrer == null)
            {
                return "";
            }
            return HttpContext.Current.Request.UrlReferrer.ToString().Trim();
        }
        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }
        public static bool IsBrowserGet()
        {
            string[] strArray = new string[] { "ie", "opera", "netscape", "mozilla" };
            string str = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < strArray.Length; i++)
            {
                if (str.IndexOf(strArray[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }

        public static bool IsGet()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("GET");
        }

        public static bool IsPost()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("POST");
        }

        public static bool IsSearchEnginesGet()
        {
            string[] strArray = new string[] { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom" };
            string str = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            for (int i = 0; i < strArray.Length; i++)
            {
                if (str.IndexOf(strArray[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }
        public static bool isLocalURL()
        {
            string met = HttpContext.Current.Request.ServerVariables["Request_Method"];
            if (met == "POST")
            {
                if (HttpContext.Current.Request.UrlReferrer == null)
                {
                    return true;
                }
                else
                {
                    string url = HttpContext.Current.Request.UrlReferrer.DnsSafeHost;
                    if (url.IndexOf("jizhang.com") != -1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            else
            {
                return true;
            }
        }

        public static void SaveRequestFile(string path)
        {
            if (HttpContext.Current.Request.Files.Count > 0)
            {
                HttpContext.Current.Request.Files[0].SaveAs(path);
            }
        }

        public static void ClearSession(string sessionName)
        {
            HttpContext.Current.Session.Remove(sessionName);
        }

        public static void SetSession(string sessionName, object value)
        {
            if (HttpContext.Current.Session[sessionName] == null)
            {
                HttpContext.Current.Session.Add(sessionName, value);
            }
            else
            {
                HttpContext.Current.Session[sessionName] = value;
            }
        }

        public static string GetSession(string sessionName)
        {
            object sessionObj = GetSessionObj(sessionName);
            if (sessionObj == null)
            {
                return "";
            }
            return sessionObj.ToString();
        }

        public static object GetSessionObj(string sessionName)
        {
            return HttpContext.Current.Session[sessionName];
        }

        public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
        {
            string str = p_SrcString;
            if (p_Length < 0)
            {
                return str;
            }
            byte[] bytes = Encoding.Default.GetBytes(p_SrcString);
            if (bytes.Length <= p_Length)
            {
                return str;
            }
            int length = p_Length;
            int[] numArray = new int[p_Length];
            byte[] destinationArray = null;
            int num2 = 0;
            for (int i = 0; i < p_Length; i++)
            {
                if (bytes[i] > 0x7f)
                {
                    num2++;
                    if (num2 == 3)
                    {
                        num2 = 1;
                    }
                }
                else
                {
                    num2 = 0;
                }
                numArray[i] = num2;
            }
            if ((bytes[p_Length - 1] > 0x7f) && (numArray[p_Length - 1] == 1))
            {
                length = p_Length + 1;
            }
            destinationArray = new byte[length];
            Array.Copy(bytes, destinationArray, length);
            return (Encoding.Default.GetString(destinationArray) + p_TailString);
        }
        /// <summary>
        /// 截取字符串函数
        /// </summary>
        /// <param name="Str">所要截取的字符串</param>
        /// <param name="Num">截取字符串的长度</param>
        /// <returns></returns>
        public static string GetSubString(string Str, int Num)
        {
            if (Str == null || Str == "")
            {
                return "";
            }
            string outstr = string.Empty;
            int n = 0;
            foreach (char ch in Str)
            {
                n += System.Text.Encoding.Default.GetByteCount(ch.ToString());

                ////修改bug,中文字符计为一个字符,by 周峻平 2008-5-28
                //if (ch >= 0x4e00 && ch <= 0x9fa5)
                //{
                //    n = n - 1;
                //}

                if (n > Num)
                {
                    break;
                }
                else
                {
                    outstr += ch;
                }
            }
            return outstr;
        }

        public static string ChkSQL(string str)
        {
            if (str == null)
            {
                return "";
            }
            str = str.Replace("'", "''");
            return str;
        }


        /// <summary>
        /// 获得html列表
        /// </summary>
        /// <param name="dt">数据源datatable</param>
        /// <param name="dtkey">关联key eg：id</param>
        /// <param name="dtvalue">关联value eg：Name</param>
        /// <param name="checkboxName">获取checkboxName eg： Request.Form["PopList"];不能为空</param>
        /// <param name="inpttitle">html中的title 可以为空</param>
        /// <param name="poplist">poplist 获得的列表 可以为空</param>
        /// <returns></returns>
        public static string GetCheckBoxListhtml(DataTable dt, string dtkey, string dtvalue, string checkboxName, string inpttitle, string poplist)
        {

            string _Str = "";
            string[] ExistList = null;
            ArrayList existArrylist = null;
            if (poplist != null)
            {
                ExistList = poplist.Split(new char[] { ',' });
                existArrylist = new ArrayList();
                for (int i = 0; i < ExistList.Length; i++)
                {
                    existArrylist.Add(ExistList[i]);
                }
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string CheckSTR = "";
                //选择记录状态参数传递
                if (!string.IsNullOrEmpty(poplist) && !"".Equals(poplist))
                {
                    if (existArrylist.Contains(dt.Rows[i]["" + dtkey + ""].ToString()))
                    {
                        if (existArrylist.IndexOf(dt.Rows[i]["" + dtkey + ""].ToString()) != -1) { CheckSTR = " checked"; } else { CheckSTR = ""; }
                    }
                }
                else
                {
                    CheckSTR = "";
                }
                string dt_value = dt.Rows[i]["" + dtvalue + ""].ToString();
                //如果值为空 就不显示
                if (dt_value == "")
                {
                    continue;
                }
                _Str += "<label><input  id=\"" + dt.Rows[i]["" + dtkey + ""] + "\"  value=\"" + dt.Rows[i]["" + dtkey + ""] + "\"" + CheckSTR + " name=\"" + checkboxName + "\" type=\"checkbox\" /><span  style=\"font-size:10px;\" title=\"" + inpttitle + "\">(" + dt.Rows[i]["" + dtkey + ""] + ")&nbsp;</span>" + dt.Rows[i]["" + dtvalue + ""] + "</label>\r";
            }

            return _Str;
        }

        public static bool IsNullOrEmptyOrDont(string value)
        {

            if (value == null || value == string.Empty || value == "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }


    }
}
